package com.pms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pms.constant.MessageConstant;
import com.pms.context.BaseContext;
import com.pms.dto.*;
import com.pms.entity.User;
import com.pms.exception.AccountNotFoundException;
import com.pms.exception.DeletionNotAllowedException;
import com.pms.exception.PasswordErrorException;
import com.pms.exception.UserAlreadyExistsException;
import com.pms.mapper.UserMapper;
import com.pms.result.PageResult;
import com.pms.result.Result;
import com.pms.service.UserService;
import com.pms.vo.UserPageQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        if(user==null){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_EXIST);
        }

        // 判断账号状态
        if(user.getStatusId()==12){
            throw new AccountNotFoundException(MessageConstant.USER_FORBIDDEN);
        }

        password= DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(user.getPassword())){
            throw new PasswordErrorException(MessageConstant.LOGIN_FAIL);
        }

        return user;
    }

    /**
     * 注册
     * @param userRegisterDTO
     */
    public void setUser(UserRegisterDTO userRegisterDTO) {
        User user1 = userMapper.getByUsername(userRegisterDTO.getUsername());
        if (user1 != null) {
            throw new UserAlreadyExistsException(MessageConstant.USER_EXIST);
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPhone(userRegisterDTO.getPhone());
        user.setRoles("owner");
        String password=DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes());
        user.setPassword(password);

        userMapper.setUser(user);
    }

    /**
     * 动态修改信息
     * @param userUpdateDTO
     */
    public void update(UserUpdateDTO userUpdateDTO) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        userMapper.update(user);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public User getUserById(Integer id) {
        User user=userMapper.getUserById(id);
        user.setPassword("******");
        return user;
    }

    /**
     * 修改密码
     * @param passwordDTO
     */
    public void updatePassword(PasswordDTO passwordDTO) {
        String oldPassword = passwordDTO.getOldPassword();
        String newPassword = passwordDTO.getNewPassword();
        String confirmPassword = passwordDTO.getConfirmPassword();

        //获取当前登录用户信息
        User user =userMapper.getUserById(BaseContext.getCurrentId());

        //校验旧密码
        String oldPasswordMD5=DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if(!oldPasswordMD5.equals(user.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_FAIL);
        }

        //校验新密码和确认密码
        if(!newPassword.equals(confirmPassword)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_NOT_EQUALS);
        }

        //设置新密码
        String newPasswordMD5=DigestUtils.md5DigestAsHex(newPassword.getBytes());
        user.setPassword(newPasswordMD5);
        userMapper.update(user);
    }

    /**
     * 根据用户名查询登录用户信息
     * @param username
     * @return
     */
    public User getByName(String username) {
        User user=userMapper.getByUsername(username);
        return user;
    }

    /**
     * 根据id查询登录用户信息
     * @param userId
     * @return
     */
    public User getById(Integer userId) {
        User user=userMapper.getUserById(userId);
        return user;
    }

    /**
     * 用户分页查询
     * @param userPageQueryDTO
     * @return
     */
    public PageResult page(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<UserPageQueryVO> page=userMapper.page(userPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            User user=userMapper.getUserById(id);
            if(user.getStatusId()==11){
                throw new DeletionNotAllowedException(MessageConstant.USER_NOT_FORBIDDEN);
            }else{
                userMapper.delete(id);
            }
        }
    }

    /**
     * 管理员修改用户信息
     */
    public void updateByAdmin(UserAdminUpdateDTO userAdminUpdateDTO) {
        User user=new User();
        BeanUtils.copyProperties(userAdminUpdateDTO,user);
        userMapper.update(user);
    }
}
